package com.technology.education.ui.teacher.home

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import com.angcyo.dsladapter.*
import com.blankj.utilcode.util.SnackbarUtils.addView
import com.google.android.material.appbar.AppBarLayout
import com.technology.education.R
import com.technology.education.data.SpKeys
import com.technology.education.data.model.Carousel
import com.technology.education.data.model.Notice
import com.technology.education.data.model.TeachOrderModel
import com.technology.education.databinding.FragmentHomeBinding
import com.technology.education.dslitem.AppStatusItem
import com.technology.education.dslitem.module.ItemTeacherHomeOrder
import com.technology.education.ext.*
import com.technology.education.widget.HomeBannerAdapter
import com.youth.banner.Banner
import com.youth.banner.indicator.CircleIndicator
import me.hgj.jetpackmvvm.base.fragment.BaseVmDbFragment
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.util.LogUtils
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.abs

class HomeFragment : BaseVmDbFragment<HomeViewModel, FragmentHomeBinding>() {

    /**提供悬停功能*/
    private val hoverItemDecoration = HoverItemDecoration()

    /**提供基本的分割线功能*/
    private val baseDslItemDecoration = DslItemDecoration()

    private val myAdapter: DslAdapter = DslAdapter().apply {
        dslAdapterStatusItem = AppStatusItem(layoutId = R.layout.item_empty_image)
        dslLoadMoreItem.onLoadMore = {
            mViewModel.loadMore()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        initSwipe()
        initVertical()
        mDatabind.appbarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            mDatabind.baseRefreshLayout.isEnabled = abs(verticalOffset) < 10
        })
    }


    /**
     * 初始化刷新swipe控件，默认关闭刷新功能
     */
    private fun initSwipe() {
        mDatabind.baseRefreshLayout.apply {
            isEnabled = false
            setProgressViewOffset(true, 40 * dpi, 70 * dpi)
            setOnRefreshListener {
                mViewModel.refresh()
            }
        }
    }

    /**
     * 初始化为垂直列表
     */
    private fun initVertical() {
        mDatabind.rvList.apply {
            addItemDecoration(baseDslItemDecoration)
            hoverItemDecoration.attachToRecyclerView(this)
            setHasFixedSize(true)
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            adapter = myAdapter
        }
    }

    override fun lazyLoadData() {
        myAdapter.render {
            updateAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_LOADING)
        }
        mViewModel.getData()
        mViewModel.getHomeData()
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun createObserver() {
        /**
         * 抢单结果
         */
        mViewModel.takeResult.observe(this) {
            //接单成功,跳转到订单详情
            if (it.state == "1") {
                customDialog(
                    "提示",
                    notify = "您保障金余额不足,是否进行充值?",
                    confirmStr = "立即充值",
                    cancelStr = "稍后充值",
                    cancel = {}) {
                    mViewModel.commitOrder()
                }
                return@observe
            }
            myAdapter.render {
                removeItem(it.id)
            }
            toast("您已接单成功")
            navigation(requireView(), R.id.action_order_to_order_detail, bundleOf("id" to it.id))
        }

        mViewModel.result.observe(this) {
            parseState(it, onSuccess = { it ->
                toPayActivity(it.money.toString(), it.id, SpKeys.PAY_TYPE_DEPOSIT)
            }, onError = { err -> toast(err.errorMsg) })
        }

        /**
         * 详情订单状态监听
         */
        observe(SpKeys.REMOVE_ORDER_FROM_LIST, String::class.java) {
            myAdapter.render {
                removeItem(it)
            }
        }

        observe(SpKeys.CHANGE_ORDER_STATUS_TAKE, String::class.java) {
            myAdapter.render {
                findItemByTag(it)?.apply {
                    (itemData as TeachOrderModel).teachOrderState = "2"
                    updateAdapterItem()
                }
            }
        }

        mViewModel.homeResult.observe(this) {
            refreshDone()
            parseState(it, onSuccess = { it ->
                mDatabind.tvStatus.apply {
                    visibility = View.VISIBLE
                    text = it.serviceStatus
                }
                setBanner(it.carouselList as ArrayList<Carousel>)
                setNotice(it.noticeList)
            })
        }

        mViewModel.orderResult.observe(this) {
            refreshDone()
            parseState(it, onSuccess = { it ->
//                myAdapter.updateAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_NONE)
                myAdapter.setLoadMoreEnable(it.total >= mViewModel.pageSize * mViewModel.pageIndex)
                myAdapter.render {
                    setPageItems(
                        it.list.toDslItemList(ItemTeacherHomeOrder::class.java) {
                            itemClick = { it ->
                                if (it.id == R.id.iv_order) {
                                    toPreviewPhoto(
                                        0,
                                        arrayListOf((itemData!! as TeachOrderModel).questionImage)
                                    )
                                } else if (it.id == R.id.btn_grab) {
//                                    videoCall("22222","2222",110)
                                    mViewModel.takeOrder(itemTag ?: "", "")
                                }
                            }
                        },
                        mViewModel.pageIndex
                    )
                }
            }, onError = { it ->
                toast(it.errorMsg)
            })
            startCountDown()
        }
    }

    private fun startCountDown() {
        Handler(Looper.getMainLooper()).postDelayed({
            mViewModel.pageIndex = 1
            mViewModel.getData()
        }, 5 * 1000)
    }

    /**
     * 设置公告信息
     */
    private fun setNotice(noticeList: List<Notice>) {
        if (noticeList.isNotEmpty()) {
            mDatabind.llNotice.visibility = View.VISIBLE
            mDatabind.viewFlipper.apply {
                removeAllViews()
                noticeList.forEach { it ->
                    addView(
                        TextView(requireContext()).apply {
                            text = it.title
                            textSize = 14f
                            isSingleLine = true
                            ellipsize = TextUtils.TruncateAt.END
                            gravity = Gravity.CENTER_VERTICAL
                            setOnClickListener { _ ->
                                it.url?.let { url ->
                                    toWebActivity(it.title, url)
                                }
                            }
                        },
                        ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT
                        )
                    )
                }
                startFlipping()
            }
        } else {
            mDatabind.llNotice.visibility = View.GONE
        }
    }

    override fun showLoading(message: String) {
        showLoadingExt(message)
    }

    override fun dismissLoading() {
        dismissLoadingExt()
    }

    /**
     * 填充banner 数据
     */
    private fun setBanner(listBanner: ArrayList<Carousel>) {
        (mDatabind.banner as Banner<Carousel, HomeBannerAdapter>).apply {
            addBannerLifecycleObserver(viewLifecycleOwner)
            listBanner?.let {
                setAdapter(HomeBannerAdapter(it))
            }
            setOnBannerListener { data, _ ->
                if (data is Carousel) {
                    data.url?.let {
                        toWebActivity("信息", it)
                    }
                }
            }
            setIndicator(CircleIndicator(context))
        }
    }

    private fun refreshDone() {
        mDatabind.baseRefreshLayout.isRefreshing = false
    }
}